package com.bwie.kanjia.controller;

import java.util.Arrays;
import java.util.Map;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.bwie.kanjia.conf.AlipayConfig;
import com.bwie.kanjia.conf.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.bwie.kanjia.entity.KeepEntity;
import com.bwie.kanjia.service.KeepService;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author ??????
 * @email 1535715783@qq.com
 * @date 2022-03-07 20:38:40
 */
@RestController
@RequestMapping("kanjia/keep")
public class KeepController {
    @Autowired
    private KeepService keepService;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = keepService.queryPage(params);

        return R.ok().put("page", page);
    }


    //生成链接
    @RequestMapping("/lj/{actId}")
    @ResponseBody
    public R lj(@PathVariable("actId") Integer actId, HttpServletRequest request){
       //生成链接，返回前台
        String token = request.getHeader("token");
        if (token!=null){
            Claims claims = jwtUtil.parseJWT(token);
            if (claims!=null&&"user".equals(claims.get("roles"))){
                String path = jwtUtil.createJWT(claims.getId(), actId + "", "path");
                return R.ok().put("lj","http://127.0.0.1:88/api/kanjia/keep/help/"+path);

            }
            return R.error("用户未登录");

        }
        return R.error("用户未登录");
    }

    @RequestMapping("/help/{path}/{userId}/{actId}")
    @ResponseBody
    public R help(@PathVariable("path") String path,
                  @PathVariable("userId")Long userId,
                  @PathVariable("actId")String actId,
                  HttpServletRequest request){
            //解析path
            Claims claims = jwtUtil.parseJWT(path);
            //如果值为空
            if (claims!=null&&"path".equals(claims.get("roles"))){
                if (!claims.getId().equals(userId+"")){//传入的userid对比
                    if (claims.getSubject().equals(actId)){//对比活动是否为同一个活动

                        return keepService.kanjia(userId,claims.getId(),Integer.parseInt(actId));
                    }else {
                        return R.error("活动信息错误");
                    }
                }else {
                    return R.error("不能给自己砍价");
                }

            }
            return R.error("链接错误");
//        }

//        return R.error("请先登录");
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{keepId}")
    public R info(@PathVariable("keepId") Integer keepId){
		KeepEntity keep = keepService.getById(keepId);

        return R.ok().put("keep", keep);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody KeepEntity keep){


        return keepService.saves(keep);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody KeepEntity keep){
		keepService.updateById(keep);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] keepIds){
		keepService.removeByIds(Arrays.asList(keepIds));

        return R.ok();
    }

    //支付

    @RequestMapping("/pay")
    public String pay(@RequestParam Integer keepId) throws Exception {
        //先查出来这个额订单
        KeepEntity keepEntity = keepService.getById(keepId);
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填 ***
        String out_trade_no = new String(keepEntity.getDdh().getBytes(),"UTF-8");
        //付款金额，必填 ***
        String w=keepEntity.getKeepMoney()+"";
        String total_amount = new String(w.getBytes(),"UTF-8");
        //订单名称，必填 ***
        String subject = new String(keepEntity.getGoodsName().getBytes(),"UTF-8");
        //商品描述，可空  ***
        String body = new String(keepEntity.getGoodsName().getBytes("ISO-8859-1"),"UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\"10m\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //输出
        return result;
    }
}
